import { ActivityAxios, HomeAxios } from "@/api";
import { UserStore } from "@/store";
import avatar1 from "@/image/new_img/activity/m_misterioso.png";
import avatar2 from "@/image/new_img/home/M_VIP_hui.png";
import avatar3 from "@/image/new_img/activity/misterioso_3.png";
import avatar4 from "@/image/new_img/activity/misterioso_4.png";
import avatar5 from "@/image/new_img/activity/misterioso_5.png";
import avatar6 from "@/image/new_img/activity/misterioso_2.png";
import avatar7 from "@/image/new_img/activity/actlevel/level_6_1.png";
import avatar8 from "@/image/new_img/activity/actlevel/level_img.png";
import avatar9 from "@/image/new_img/activity/actlevel/rankv2_rank12.png";
import avatar10 from "@/image/new_img/activity/actlevel/rankv2_rank22.png";
import avatar11 from "@/image/new_img/activity/actlevel/rankv2_rank32.png";
import avatar12 from "@/image/new_img/activity/actlevel/rankv2_rank42.png";
import avatar13 from "@/image/new_img/activity/actlevel/rankv2_rank52.png";
import avatar14 from "@/image/new_img/activity/actlevel/rankv2_rank62.png";
import level1 from "@/image/new_img/activity/actlevel/level_2_1.png";
import level2 from "@/image/new_img/activity/actlevel/level_3_1.png";
import level3 from "@/image/new_img/activity/actlevel/level_4_1.png";
import level4 from "@/image/new_img/activity/actlevel/level_5_1.png";
import { UAParser } from "ua-parser-js";
const parser = new (UAParser as any)();
declare global {
  interface Navigator {
    standalone?: boolean;
  }
}
declare global {
  interface Window {
    MyAppInterface?: any;
  }
}
export const FiltrationFun = {
  formatNumber(num) {
    // 将数字转换为字符串
    const numStr = num.toString();

    // 分离整数部分和小数部分
    const [integerPart, decimalPart] = numStr.split(".");

    // 处理整数部分，每四位用逗号分隔
    const formattedIntegerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    // 合并整数部分和小数部分
    const result = decimalPart ? `${formattedIntegerPart}.${decimalPart}` : formattedIntegerPart;
    return result;
  },
  //获取活动说明
  async getconfigDesc(type: number) {
    let list = [];
    await ActivityAxios.getActConfigDesc({ actType: type }).then((res: any) => {
      list = res.list;
    });
    return list;
  },
  //获取活动配置
  async getconfig(type: number) {
    let list = [];
    await ActivityAxios.getconfig({ acttype: type }).then((res: any) => {
      list = res.configs;
    });
    return list;
  },
  //获取分享说明
  async getWebsiteShareConfig() {
    let data = {
      shareContent: "",
      sharePicture: "",
    };
    await ActivityAxios.getWebsiteShareConfig().then(res => {
      data = res;
    });
    return data;
  },
  //获取当前设备操作系统
  getDeviceType() {
    const userAgent = navigator.userAgent || navigator.vendor;

    if (/android/i.test(userAgent)) {
      return "Android";
    }
    if (/iPad|iPhone|iPod/.test(userAgent)) {
      return "iOS";
    }
    return "Android";
  },
  urlB64ToUint8Array(base64String) {
    const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/");

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  },
  //获取订阅
  subscribeUser(swReg) {
    const userStore = UserStore();
    HomeAxios.getUserPwaServerKeys().then(res => {
      const applicationServerKey = this.urlB64ToUint8Array(res.serverKey);
      swReg.pushManager
        .subscribe({
          userVisibleOnly: true,
          applicationServerKey: applicationServerKey,
        })
        .then(function (_subscription) {
          if (userStore.isLogin) {
            HomeAxios.addUserPwaSub({ subscription: JSON.stringify(applicationServerKey) }).then(
              res => {
                console.log("成功了吗", res);
              },
            );
          }
        })
        .catch(function (err) {
          console.log(err, "订阅失败:看看code ", err.code);
        });
    });
  },
  //分享faceBook,x,whateApp,快手抖音等平台
  async shareTerrace(data) {
    //打开浏览器自带的分享
    if (data.name === "Mais") {
      if (navigator.share) {
        try {
          // 调用分享功能
          await navigator.share({
            title: data.title,
            text: data.content,
            url: data.url, // 可选分享的链接
          });
          console.log("分享成功");
        } catch (error) {
          console.error("分享失败:", error);
        }
      } else {
        console.log("当前浏览器不支持 Web Share API");
      }
    }
    if (data.name === "Facebook") {
      const urlToShare = encodeURIComponent(data.url); // 要分享的链接
      const shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${urlToShare}`;
      window.open(shareUrl, "_blank");
      // (window as any).FB.ui(
      //   {
      //     method: "share",
      //     href: data.url, // 分享的链接
      //     quote: data.content,
      //     hashtag: data.title, // 可选：自定义分享时的标签
      //     mobile_iframe: true, // 适配移动端
      //   },
      //   (response: any) => {
      //     if (response && !response.error_message) {
      //       console.log("分享成功");
      //     } else {
      //       console.log("分享失败");
      //     }
      //   },
      // );
    }
    if (data.name === "WhatsApp") {
      const text = encodeURIComponent(data.content + ":" + data.url); // 分享内容与链接
      const whatsappUrl = `https://wa.me/?text=${text}`;

      // 在新窗口中打开分享链接
      window.open(whatsappUrl, "_blank");
    }
    if (data.name === "Telegram") {
      const url = encodeURIComponent(data.url); // 要分享的链接
      const text = encodeURIComponent(data.content); // 要分享的文本内容
      const telegramUrl = `https://t.me/share/url?url=${url}&text=${text}`;
      // 在新窗口中打开分享链接
      window.open(telegramUrl, "_blank");
    }
    if (data.name === "Instagram") {
      const instagramAppUrl = "instagram://camera"; // 尝试打开 Instagram 应用
      const instagramWebUrl = "https://www.instagram.com"; // Instagram 网页版

      // 尝试打开 Instagram 应用
      const openApp = setTimeout(() => {
        window.location.href = instagramWebUrl; // 若超时，打开网页版
      }, 1000); // 等待时间

      // 使用 iframe 尝试打开 Instagram 应用（部分浏览器不允许直接用 window.location.href）
      const iframe = document.createElement("iframe");
      iframe.style.display = "none";
      iframe.src = instagramAppUrl;
      document.body.appendChild(iframe);

      // 清理计时器
      window.addEventListener("blur", () => clearTimeout(openApp));
    }
    if (data.name === "Kwai") {
      const appUrl = "kwai://home";
      const webUrl = "https://www.kwai.com/foryou";

      // 创建隐藏的 iframe
      const iframe = document.createElement("iframe");
      iframe.style.display = "none";
      iframe.src = appUrl;

      document.body.appendChild(iframe);

      // 延时检测，若 kwai:// 未能打开，跳转到网页版
      setTimeout(() => {
        document.body.removeChild(iframe); // 清理 iframe
        window.location.href = webUrl; // 跳转到快手网页版
      }, 1000); // 延时 1.5 秒
    }
    if (data.name === "Twitter") {
      const text = data.content; // 自定义分享文本
      const url = data.url; // 要分享的链接

      // 推特分享 URL
      const twitterUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(
        text,
      )}&url=${encodeURIComponent(url)}`;

      // 打开新窗口进行分享
      window.open(twitterUrl, "_blank");
    }
    if (data.name === "TikTok") {
      const appLink = "tiktok://home"; // 直接跳转到 TikTok 首页
      const fallbackUrl = "https://www.tiktok.com"; // 如果用户没有安装 TikTok，则跳转到网页版

      // 尝试打开 TikTok 应用
      const newWindow = window.open(appLink, "_blank");
      if (!newWindow) {
        // 如果失败，打开网页版
        window.location.href = fallbackUrl;
      }
    }
    if (data.name === "Youtube") {
      window.open("https://www.youtube.com", "_blank");
    }
  },
  //生成超级会员日排行榜数据
  generateLeaderboardData(arr) {
    const arrimg = [
      avatar1,
      avatar2,
      avatar3,
      avatar4,
      avatar5,
      avatar6,
      avatar7,
      avatar8,
      avatar9,
      avatar10,
      avatar11,
      avatar12,
      avatar13,
      avatar14,
    ];
    arr = arr.map(item => {
      return {
        ...item,
        avatar: arrimg[Math.floor(Math.random() * arrimg.length)], // 随机选择头像
        userName: this.generateUserName(), // 随机生成用户名
      };
    });
    return arr;
  },
  // 随机生成用户名的函数
  generateUserName() {
    const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    const len = Math.floor(Math.random() * 2) + 8; // 生成长度为8或9的字符串
    let name = "";
    for (let i = 0; i < len; i++) {
      name += chars[Math.floor(Math.random() * chars.length)];
    }
    // 替换中间3位为 '*'
    const mid = Math.floor(len / 2);
    return name.slice(0, mid - 1) + "***" + name.slice(mid + 2);
  },

  //判断是那pwa或者apk的环境
  detectEnvironment() {
    const isPWA =
      window.matchMedia("(display-mode: standalone)").matches || window.navigator.standalone;
    const isApp = window["hy_is_apk"] !== undefined;

    if (isPWA) {
      return "pwa";
    } else if (isApp) {
      return "apk";
    } else {
      return "Browser";
    }
  },
  //获取活动等级的图标
  getActLeve() {
    const userStore = UserStore();
    const level = userStore.userInfoDetails.account.level;
    if (level === 0) {
      return avatar8;
    } else if (level === 1) {
      return level1;
    } else if (level === 2) {
      return level2;
    } else if (level === 3) {
      return level3;
    } else if (level === 4) {
      return level4;
    } else if (level === 5) {
      return avatar7;
    }
  },
  // 随机生成11位字符函数
  randomizedString() {
    const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    let name = "";
    for (let i = 0; i < 11; i++) {
      name += chars[Math.floor(Math.random() * chars.length)];
    }
    return name;
  },
  parseQueryString(queryString) {
    const queryPart = queryString.split("?")[1] || "";
    const urlParams = new URLSearchParams(queryPart);
    const paramsArray: any = [];
    urlParams.forEach((value, key) => {
      paramsArray.push({ [key]: value });
    });

    return paramsArray;
  },
  //事件上报
  setReportEvent(eventName) {
    // ViewContent访问点击,CompleteRegistration完成注册,登录SubmitApplication,进入游戏StartTrial,进入充值页面AddToCart,充值拉单成功InitiateCheckout,首充和首充金额Purchase,安装pwa+apk CustomizeProduct
    if (sessionStorage.getItem("advid")) {
      const os = parser.getOS().name + " " + parser.getOS().version;
      const data: any = {
        advid: sessionStorage.getItem("advid"),
        eventName: eventName,
        os: os,
        uniqid: localStorage.getItem("deviceUniqueKey"),
      };
      HomeAxios.setReportEvent(data);
    }
  },
  //转化小数位
  ensureTwoDecimalPlaces(num) {
    if (num) {
      // 将数字转换为字符串
      const numStr = num.toString();

      // 检查是否有小数点
      if (numStr.includes(".")) {
        // 获取小数部分的长度
        const decimalPart = numStr.split(".")[1];
        const decimalLength = decimalPart.length;

        // 如果小数部分长度小于2，则补足两位
        if (decimalLength < 2) {
          return parseFloat(numStr + "0".repeat(2 - decimalLength)).toFixed(2);
        } else {
          // 如果已经有两位或更多小数位，直接返回
          return numStr;
        }
      } else {
        // 如果没有小数部分，直接补足两位
        return parseFloat(numStr + ".00").toFixed(2);
      }
    } else {
      return "0.00";
    }
  },
  //获取设备唯一deviceId的给登录，验证token 获取新token获取环境
  getDeviceId() {
    //获取环境paw , apk ，还是浏览器
    const settingType = this.detectEnvironment();
    //设备系统名称
    const osName = parser.getOS().name;
    //版本号
    const version = parser.getOS().version;
    if (settingType === "pwa") {
      if (osName === "Android") {
        return version + "(安卓pwa)";
      } else if (osName === "iOS") {
        return version + "(iOS安卓pwa)";
      } else {
        return version + `(${osName}pwa)`;
      }
    }
    if (settingType === "apk") {
      if (osName === "Android") {
        return version + "(安卓APP)";
      } else if (osName === "iOS") {
        return version + "(iOS安卓APP)";
      } else {
        return version + "(安卓APP)";
      }
    }
    if (settingType === "Browser") {
      if (osName === "Android") {
        return version + "(安卓浏览器)";
      } else if (osName === "iOS") {
        return version + "(iOS浏览器)";
      } else {
        return version + `(${osName}浏览器)`;
      }
    }
  },
};
